#include "searchalgorithm.h"
#include <chrono>

SearchAlgorithm::SearchAlgorithm() : maxDepth(100), maxNodes(100000), timeLimit(30.0), nodesGenerated(0), nodesExpanded(0)
{
}

SearchAlgorithm::SearchAlgorithm(const std::string& name) 
    : algorithmName(name), maxDepth(100), maxNodes(100000), timeLimit(30.0), nodesGenerated(0), nodesExpanded(0)
{
}

SearchAlgorithm::~SearchAlgorithm()
{
}

bool SearchAlgorithm::shouldStop(int nodesExpanded, int currentDepth, double elapsedTime) const
{
    if (maxDepth > 0 && currentDepth > maxDepth) {
        return true;
    }
    
    if (maxNodes > 0 && nodesExpanded > maxNodes) {
        return true;
    }
    
    if (timeLimit > 0 && elapsedTime > timeLimit) {
        return true;
    }
    
    return false;
}

std::vector<int> SearchAlgorithm::buildSolution(std::shared_ptr<SearchNode> goalNode) const
{
    std::vector<int> solution;
    
    if (!goalNode) {
        return solution;
    }
    
    std::shared_ptr<SearchNode> current = goalNode;
    while (current && !current->isRoot()) {
        solution.insert(solution.begin(), current->getAction());
        current = current->getParent();
    }
    
    return solution;
}

std::string SearchAlgorithm::actionToString(int action) const
{
    switch (action) {
        case 0: return "上";
        case 1: return "下";
        case 2: return "左";
        case 3: return "右";
        default: return "未知";
    }
}